/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: UpdateAgent.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.baselib.update;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;

import io.bhex.baselib.R;

import java.io.File;
import java.lang.ref.WeakReference;

import io.bhex.baselib.network.HttpUtils;
import io.bhex.baselib.network.params.IParams;
import io.bhex.baselib.network.response.ResponseListener;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.MD5Utils;
import io.bhex.baselib.utils.NetworkUtils;
import io.bhex.baselib.utils.SP;


public class UpdateAgent {

    public static final String DOWNLOAD_ID = "download_id";

    public static final String DOWNLOAD_MD5 = "download_md5";

    public static final String UPGRADE_FOLDER = "/update";

    private static UpdateReturnListener updateListener = null;

    private static WeakReference<Context> context;

    public static <T extends UpdateResponseIntf> void updateForce(Context ctx, IParams params, Class<T> clazz, @NonNull ResponseListener<T> listener) {
        context = new WeakReference<Context>(ctx);

        UpdateConfig.setUpdateForce(true);
        if (!NetworkUtils.isWifiConnected(ctx)) {
            if (updateListener != null) {
                updateListener.onNoWifi();
            }
            return;
        }
        getUpdateInfo(params, clazz, listener);
    }

    public static <T extends UpdateResponseIntf> void update(Context ctx, IParams params, Class<T> clazz, @NonNull ResponseListener<T> listener) {
        context = new WeakReference<Context>(ctx);

        UpdateConfig.setUpdateForce(false);
        if (!NetworkUtils.isWifiConnected(ctx)) {
            if (updateListener != null) {
                updateListener.onNoWifi();
            }
//            ToastUtils.showLong(ctx,"请打开WIFI进行下载");

            if (UpdateConfig.isUpdateOnlyOnWifi())
                return;
        }

        getUpdateInfo(params, clazz, listener);
    }


    private static <T extends UpdateResponseIntf> void getUpdateInfo(IParams params,
                                                                     Class<T> clazz,
                                                                     ResponseListener<T> listener) {
        if (context == null || context.get() == null)
            return;

        HttpUtils.getInstance().request(params, clazz, new UpdateResponseWrapper<T>(context.get(), listener, updateListener));
    }

    public static void ignored(Context context, UpdateResponseIntf response) {
        UpdateConfig.saveIgnoredMd5(context, response.getFileMd5());
    }


    public static void setOnUpdateReturnListener(UpdateReturnListener listener) {
        updateListener = listener;
    }

    public static UpdateReturnListener getOnUpdateReturnListener() {
        return updateListener;
    }


    public static void startInstall(Context context, File file) {
        Intent localIntent = new Intent("android.intent.action.VIEW");
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        context.startActivity(localIntent);
    }

    public static File getUpdateFileDir() {
        final File file = new File(Environment.getExternalStorageDirectory() + File.separator +
                context.get().getPackageName() + UPGRADE_FOLDER);
        if (!(file.exists() && file.isDirectory())) {
            file.mkdirs();
        }
        return file;
    }

    public static void downLoad(Context context, UpdateResponseIntf response) {
        if (response == null || response.getFileUrl() == null) {
            return;
        }

        final File file = getUpdateFileDir();

        final File apkFile = new File(file, response.getFileMd5() + ".apk");
        if (apkFile.exists()) {
            if (MD5Utils.getFileMD5(apkFile).equals(response.getFileMd5())) {
                startInstall(context, apkFile);
                return;
            } else {
                if (!apkFile.delete()) {
                    apkFile.deleteOnExit();
                }
            }
        }

        //清空文件夹
        for (File tmp : file.listFiles()) {
            if (!tmp.delete())
                tmp.deleteOnExit();
        }

        DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(response.getFileUrl()));
        request.setTitle(context.getResources().getString(R.string.app_name));
        request.setDescription("正在下载更新...                                        ");
        request.setDestinationUri(Uri.fromFile(apkFile));
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        request.setShowRunningNotification(true);
        request.setVisibleInDownloadsUi(false);

        try {
            manager.remove(SP.get(DOWNLOAD_ID, -1l));
        } catch (Exception e) {
            DebugLog.e(e);
        }

        SP.set(DOWNLOAD_ID, manager.enqueue(request));
        SP.set(DOWNLOAD_MD5, response.getFileMd5());
    }
}
